package com.jinxin.platform.cdacscontrolmgr.utils;

import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-02-05
 * @Author: Lingnan
 **/
public class DateUtil {
    public static final String DATE_TIME_PATTERRN = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_TIME_PATTERRN2 = "yyyyMMddHHmmssSSS";

    public static String getCurrentDateTimeStr(){
        SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_PATTERRN2);
        return format.format(new Date());
    }

    public static String getLast7DaysDate(){
        Calendar c = Calendar.getInstance();
        //过去七天
        c.setTime(new Date());
        c.add(Calendar.DATE, - 7);
        Date d = c.getTime();
        SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_PATTERRN);
        return format.format(d);
    }
    /**
     * 判断字符串是否为合法的日期格式
     * @param dateStr 待判断的字符串
     * @return
     */
    public static boolean isValidDate(String dateStr,String pattern){
        if(StringUtils.isEmpty(dateStr)){return false;}
        //判断结果 默认为true
        boolean judgeresult=true;
        //1、首先使用SimpleDateFormat初步进行判断，过滤掉注入 yyyy-01-32 或yyyy-00-0x等格式
        //此处可根据实际需求进行调整，如需判断yyyy/MM/dd格式将参数改掉即可
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try{
            //增加强判断条件，否则 诸如2022-02-29也可判断出去
            format.setLenient(false);
            Date date =format.parse(dateStr);
            System.out.println(date);
        }catch(Exception e){
            judgeresult=false;
        }
        //由于上述方法只能验证正常的日期格式，像诸如 0001-01-01、11-01-01，10001-01-01等无法校验，此处再添加校验年费是否合法
        String yearStr=dateStr.split("-")[0];
        if(yearStr.startsWith("0") || yearStr.length()!=4){
            judgeresult = false;
        }
        return judgeresult;
    }

    public static Date string2Date(String dateTime){
        if(!isValidDate(dateTime,DATE_TIME_PATTERRN)){return null;}
        SimpleDateFormat df = new SimpleDateFormat(DATE_TIME_PATTERRN);
        try {
            return df.parse(dateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getCurrentDayYMD(String pattern) {
        Calendar seekedDate = Calendar.getInstance();
        seekedDate.setTime(new Date());
        seekedDate.set(Calendar.DAY_OF_MONTH, seekedDate.get(Calendar.DAY_OF_MONTH));
        pattern = StringUtil.isEmpty(pattern) ? DATE_TIME_PATTERRN : pattern;
        DateFormat df = new SimpleDateFormat(pattern);
        return df.format(seekedDate.getTime());
    }

    public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {
        String newPattern = format;
        if(StringUtil.isEmpty(format)){
            newPattern = DATE_TIME_PATTERRN;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(newPattern);
        return localDateTime.format(formatter);
    }
    //毫秒转LocalDateTime
    public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    public static String getLastDay(){
        LocalDate nowDate = LocalDate.now();
        LocalDate yesterDay = nowDate.minusDays(1);
        return yesterDay.toString();
    }

    public static LocalDateTime timeString2LocalDateTime(String timeStr,String pattern){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(timeStr,df);
    }

    /***
     * 判断字符串是否是yyyy-MM-dd格式
     * @param mes 字符串
     * @return boolean 是否是日期格式
     */
    public static boolean isDate(String mes){
        String format = "([0-9]{4})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])";
        Pattern pattern = Pattern.compile(format);
        Matcher matcher = pattern.matcher(mes);
        if (matcher.matches()) {
            pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
            matcher = pattern.matcher(mes);
            if (matcher.matches()) {
                int y = Integer.parseInt(matcher.group(1));
                int m = Integer.parseInt(matcher.group(2));
                int d = Integer.parseInt(matcher.group(3));
                if (d > 28) {
                    Calendar c = Calendar.getInstance();
                    c.set(y, m-1, 1);
                    //每个月的最大天数
                    int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
                    return (lastDay >= d);
                }
            }
            return true;
        }
        return false;

    }

    public static String getLastSeconds(int seconds){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = new GregorianCalendar();
        Date date = new Date();
        c.setTime(date);//设置参数时间
        c.add(Calendar.SECOND,-seconds);
        date=c.getTime();
        return df.format(date);
    }

    public static LocalDateTime getNextMinTime(LocalDateTime localDateTime,int minutes){
        Date date = localDateTimeConvertToDate(localDateTime);
        Calendar c = new GregorianCalendar();
        c.setTime(date);//设置参数时间
        c.add(Calendar.MINUTE,minutes);
        date=c.getTime();
        return dateConvertToLocalDateTime(date);
    }

    //将java.util.Date 转换为java8 的java.time.LocalDateTime,默认时区为东8区
    public static LocalDateTime dateConvertToLocalDateTime(Date date) {
        return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
    }

    //将java8 的 java.time.LocalDateTime 转换为 java.util.Date，默认时区为东8区
    public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
    }

    public static long getMinituesFromDateTime(LocalDateTime dateTime){
        Date date = localDateTimeConvertToDate(dateTime);
        long start = date.getTime();
        long end = System.currentTimeMillis();
        return (end - start) / (1000 * 60);
    }

    public static long getDifferSeconds(Date startDate, Date endDate) {
        return (endDate.getTime()-startDate.getTime())/1000;
    }

    public static long getDifferMin(LocalDateTime startDate, LocalDateTime endDate) {
        if(startDate == null || endDate == null){
            return 0;
        }
        long differ = endDate.toEpochSecond(ZoneOffset.of("+8")) - startDate.toEpochSecond(ZoneOffset.of("+8"));
        return differ / 60;
    }

    public static String getDifferTime(Long totalMin) {
        if(totalMin == null || totalMin == 0){return "0分";}
        long differ = totalMin * 60;
        long day = differ / (60 * 60) / 24;
        long hour = differ / (60 * 60) % 24;
        long min = differ  % (60 * 60) / 60;
        return (day > 0 ? day + "天" : "") +
                (hour > 0 ? hour + "小时" : "") +
                (min > 0 ? min + "分" : "");
    }

    public static void main(String[] args) {
        Date date1 = string2Date("2023-03-13 10:10:30");
        System.out.println(date1);
        System.out.println(getDifferSeconds(date1,new Date()));
//        System.out.println(string2Date("2022-02-28 15:25:36"));
//        System.out.println(getCurrentDateTimeStr());
        System.out.println(getLastDay());

        Timer timer = new Timer();
        timer.schedule(new TestTask(),date1);

    }

    static class TestTask extends TimerTask{

        @Override
        public void run() {
            System.out.println("执行了");

        }
    }
}
